using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SoftDemo.Application.Common.Interface;
using SoftDemo.Application.RequetDto;
using SoftDemo.Application.Response;
using SoftDemo.Domain.Entity;
using SoftDemo.Infrastructrue.Utils;

namespace  SoftDemo.Api.Controllers
{
     [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private readonly IRepository<AppUser> _appUser;
        private readonly IIdentityService _identityService;

        public UsersController(IRepository<AppUser> appUser,IIdentityService identityService)
        {
            _appUser = appUser;
            _identityService=identityService;
        }
        
        [AllowAnonymous]
        [HttpPost("/users")]
        public async Task<AppUser> Post(UserForAuthDto userForAuthDto)
        {
            // throw new Exception("我就是测试一下");
            var appUser = new AppUser
            {
                Username = userForAuthDto.Username,
                Password = userForAuthDto.Password
            };

            await _appUser.AddAsync(appUser);
            return  appUser;
        }

        [AllowAnonymous]
        [HttpPost("/token")]
        public async Task<string> ValidateUser(UserForAuthDto userForAuthDto)
        {
            var token=await _identityService.ValidateUserAsync(userForAuthDto);

            return token.SerializeObject();
        }

        [AllowAnonymous]
        [HttpPost("/refresh")]
        public async Task<string> RefreshToken(AppTokenDto appTokenDto)
        {
            var token=await _identityService.RefreshTokenAsync(appTokenDto);

            return token.SerializeObject();
        }
    }
}